import React, {
  useCallback,
  useEffect,
  useReducer,
  useRef,
  useState,
} from 'react';
import { Engine } from '../DesignerModels';

const isRef = (current: any) => current && typeof current !== 'undefined';

export const useEngine = (id: string) => {
  const [, forceUpdate] = useReducer((v) => v + 1, 0);

  const compute = useCallback(() => {
    //更新全局状态
    forceUpdate();
  }, [forceUpdate]);

  const engine = useRef<Engine>(
    new Engine({
      //设计器引擎
      id,
      compute,
      example: null,
    }),
  );

  useEffect(() => {
    if (isRef(engine.current)) {
      compute();
    }
  }, [id]);

  return {
    engine: engine.current,
  };
};
